import json
import time
from collections import OrderedDict

import jwt
from rest_framework import response, status
from rest_framework.viewsets import ModelViewSet

from ..users.models import User

from django.http import JsonResponse

from django.shortcuts import render
from django.views import View

from meiduo_mall import settings


# Create your views here.
# from utils.views import LoginRequiredJSONMixin

class Tokens(View):

    def post(self, request):

        json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get('password')

        # users = User.objects.filter(username=username)
        try:
            users = User.objects.get(username=username)
        except Exception:
            return JsonResponse({'code': 0, 'errmsg': '用户不存在'})

        user_id = 1

        tokens = make_token(username)
        # token = str(tokens, 'utf-8')
        # token = str(tokens)
        result = {'code': 200, 'username': username, 'token': tokens.decode(), 'id': user_id}
        return JsonResponse(result)
        # return JsonResponse({'code': 0, 'username': username})


def make_token(username, expire=3600 * 24):

    key = settings.JWT_TOKEN_KEY
    now_t = time.time()
    payload_data = {'username': username, 'exp': now_t + expire}
    return jwt.encode(payload_data, key, algorithm='HS256')

'''
from apps.users.models import User
from datetime import date
from rest_framework.response import Response


from rest_framework.views import APIView
# 基类
from rest_framework.generics import GenericAPIView
# 一般和Mixin配合使用      mixin(增删改查)
from rest_framework.generics import ListAPIView,RetrieveAPIView
# 三级视图 已经继承了Mixin http方法都不用写了
'''
from rest_framework.views import APIView
from datetime import date
from rest_framework.response import Response
from ..users.models import User

class DailyActiveAPIView(View):

    def get(self, request):

        today = date.today()
        count = User.objects.filter(last_login__gte=today).count()

        return JsonResponse({'count': count})



class DailyOrderCountAPIView(View):

    def get(self, request):
        today = date.today()
        count = User.objects.filter(orderinfo__create_time__gte=today).count()

        return JsonResponse({'count': count})

class NewAddUsers(View):

    def get(self, request):
        today = date.today()
        count = User.objects.filter(date_joined__gte=today).count()

        return JsonResponse({'count': count})



#################用户管理#####################
from rest_framework.generics import ListAPIView, GenericAPIView,ListCreateAPIView
from rest_framework.views import APIView
from apps.users.models import User
from apps.meiduo_admin.serializers import UserSerializers, SKUIMageSerializers, ShowSKUINFI, SKU_admin_CRUDSerializers, \
    Show_Categories_Serializers, Show_SPU_Serializers, SpecsModelSerializers, PermissionModelSerializer, \
    ContentTypeModelSerializer, Group_Serializer, User_Serializer, Admin_PeopleGroup
from rest_framework.pagination import LimitOffsetPagination, PageNumberPagination
from rest_framework.response import Response
from goods.models import SKUImage, SKU

class PageNum(PageNumberPagination):
    page_size = 5

    page_size_query_param = 'pagesize'
    max_page_size = 20

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('lists', data),
            ('page', self.page.number),
            ('pages', self.page.paginator.num_pages),
            ('pagesize', self.page.paginator.per_page)
        ]))


class UserAdmin(ListCreateAPIView):

    # def get(self, request):
    #
    #     token = request.META.get('HTTP_AUTHORIZATION')
    #     # token = request.META.get('AUTHORIZATION')
    #     users = User.objects.all()
    #     serializer = UserSerializers(users)
    #     # serializer = {}
    #     # s = serializer.data
    #     # return Response(serializer.data)
    #     return JsonResponse({'code': 200, 'serializer': serializer.data})

    queryset = User.objects.all()
    serializer_class = UserSerializers
    pagination_class = PageNum

    def get_queryset(self):

        keyword = self.request.query_params.get('keyword')

        if keyword:
            return User.objects.filter(mobile__contains=keyword)

        return User.objects.all()



# 使用ListAPIView完成商品信息的展示
class SKUImageView(ListAPIView):


    queryset = SKUImage.objects.all()

    serializer_class = SKUIMageSerializers
    pagination_class = PageNum



# 使用ModelViewSet完成商品图片信息的展示
class ImageModelViewSets(ModelViewSet):

    queryset = SKUImage.objects.all()

    serializer_class = SKUIMageSerializers
    pagination_class = PageNum


    def create(self, request, *args, **kwargs):

        # 获取图片二进制
        image = request.data.get('image')
        image_data = image.read()

        # 获取图片id
        sku_id = request.data.get('sku')

        try:
            SKU.objects.get(id=sku_id)
        except Exception:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 创建fastdfs客户端
        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        result = client.upload_by_buffer(image_data)

        if result['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_400_BAD_REQUEST)
        file_id = result.get('Remote file_id')
        new_image = SKUImage.objects.create(sku_id=sku_id, image=file_id)
        return Response(status=status.HTTP_201_CREATED)






# 使用ListAPIView完成新增商品图片的name和id
class ShowSKU(ListAPIView):

    serializer_class = ShowSKUINFI
    queryset = SKU.objects.all()



class SKU_admin_CRUD(ModelViewSet):

    def get_queryset(self):

        keyword = self.request.query_params.get('keyword')

        if keyword:
            return SKU.objects.filter(name__contains=keyword)
        return SKU.objects.all()
    # queryset = SKU.objects.all()
    serializer_class = SKU_admin_CRUDSerializers
    pagination_class = PageNum



from goods.models import GoodsCategory, SPUSpecification, SPU
##################三级试图的分类#######################
class Show_Categories_View(ListAPIView):

    queryset = GoodsCategory.objects.filter(subs=None)
    serializer_class = Show_Categories_Serializers
    # pagination_class = PageNum


####################SPU数据#####################
class Show_SPUView(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = Show_SPU_Serializers


class SPU_SpecView(APIView):

    def get(self, request, spu_id):

        specs = SPUSpecification.objects.filter(spu_id=spu_id)

        serializer = SpecsModelSerializers(specs, many=True)

        return Response(serializer.data)



################权限###################
from django.contrib.auth.models import Permission

class PermissionModel(ModelViewSet):

    queryset = Permission.objects.all()
    serializer_class = PermissionModelSerializer
    pagination_class = PageNum


from django.contrib.auth.models import ContentType

class Content_Type_View(ListAPIView):
    queryset = ContentType.objects.all()
    serializer_class = ContentTypeModelSerializer


#######################组管理############
from django.contrib.auth.models import Group

class GroupModelSet(ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = Group_Serializer
    pagination_class = PageNum

from django.contrib.auth.models import Permission

class GroupPermission(ListAPIView):
    queryset = Permission.objects.all()
    serializer_class = PermissionModelSerializer


###########用户管理员设置###########
from apps.users.models import User

class User_Model_ViewSet(ModelViewSet):
    queryset = User.objects.filter(is_staff=True)
    serializer_class = User_Serializer
    pagination_class = PageNum


#################管理员管理获取所有组###########
class Admin_PeopleGroup(ListAPIView):

    serializer_class = Admin_PeopleGroup
    queryset = Group.objects.all()